package edu.ynu.e_platform.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import edu.ynu.e_platform.common.security.config.SecurityContants;
import edu.ynu.e_platform.entities.Customer;
import edu.ynu.e_platform.entities.User;
import edu.ynu.e_platform.service.BusinessService;
import edu.ynu.e_platform.service.CustomerService;
import edu.ynu.e_platform.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author manwen Yang
 */
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private UserService Svc;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = getAuthToken(request);
        //如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //执行认证
        if(StrUtil.isBlank(token)){
            throw new Exception("无token,请重新登录");
        }

        //获取token中的userId
        String userId;
        try {
            userId = JWT.decode(token).getAudience().get(0);
        }catch (Exception e) {
            throw new Exception("token验证失败，请重新登录");
        }

        //根据token中的user id 查询数据库
        User user = Svc.findUser(Long.valueOf(userId));
        if(user == null){
            throw new Exception("用户不存在，请重新登录");
        }
        //用户密码加签验证 token
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            verifier.verify(token); //验证token
        }catch (JWTVerificationException e){
            throw new RuntimeException("401");
        }

        return true;
    }

    private String getAuthToken(HttpServletRequest request) {
        String authToken = null;
        String authorization = request.getHeader(SecurityContants.HEADER_STRING);
        if (StringUtils.hasText(authorization) && authorization.startsWith(SecurityContants.TOKEN_PREFIX)) {
            authToken = authorization.substring(7);
        }
        return authToken;
    }
}
